package com.klikmee.sms.chat.web.listeners;

import java.util.Date;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;

import com.klikmee.sms.cef.CoreAdapter;
import com.klikmee.sms.cef.services.Service;
import com.klikmee.sms.chat.web.dao.AnswerDAO;
import com.klikmee.sms.services.chat.model.Answer;
import com.klikmee.sms.services.chat.model.Question;

/**
 * This class can be registered to listen for new request message event. When
 * invoked it will send canned info as a regular service step. Canned response
 * is saved as response message.
 * 
 * @author makcro
 * 
 */
public class RegularCannedInfoSender implements Observer {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(RegularCannedInfoSender.class);
	/**
	 * Ref to the Core adapter used to communicate with the core
	 */
	private CoreAdapter coreAdapter = null;
	/**
	 * Canned answer charging id
	 */
	private Long infoChargingId;
	/**
	 * Id of this instance of the service
	 */
	private Long serviceId;

	/**
	 * Text of the canned response
	 */
	private String cannedResponseText = null;
	/**
	 * Reference to the dao instance used to store answers
	 */
	private AnswerDAO answerDAO = null;

	/**
	 * Sends canned response to the customer and stores the answer to the
	 * database.
	 */
	@Override
	public void update(Observable o, Object arg) {

		// check for the type of argument
		if (!(arg instanceof Question)) {
			logger.fatal(String.format("Unexpected argument type. Expected instance of %s", Question.class.getCanonicalName()));
			return;
		}

		// send response
		Question question = (Question) arg;

		Long coreId = this.coreAdapter.sendMessage(this.infoChargingId, this.serviceId, Service.SERVICE_FLAG_SEMANTIC_OK, question.getCoreID(),
				this.cannedResponseText);

		// save the answer
		Answer answer = new Answer();
		answer.setToNumber(question.getFromNumber());
		answer.setAnswer(this.cannedResponseText);
		answer.setDateAnswered(new Date());
		answer.setFromNumber(question.getToNumber());
		answer.setQuestion(question);
		answer.setCoreID(coreId);
		// create answer
		this.answerDAO.create(answer);

		logger.info(String.format("Successfully send canned info with core id = [%s]", coreId));
	}

	public void setAnswerDAO(AnswerDAO answerDAO) {
		this.answerDAO = answerDAO;
	}

	public void setCannedResponseText(String cannedResponseText) {
		this.cannedResponseText = cannedResponseText;
	}

	public void setCoreAdapter(CoreAdapter coreAdapter) {
		this.coreAdapter = coreAdapter;
	}

	public void setInfoChargingId(Long infoChargingId) {
		this.infoChargingId = infoChargingId;
	}

	public void setServiceId(Long serviceId) {
		this.serviceId = serviceId;
	}
}
